package cpoo.video;

import java.awt.Image;

import javax.media.Buffer;
import javax.media.Codec;
import javax.media.Format;
import javax.media.ResourceUnavailableException;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;
import javax.media.util.ImageToBuffer;

public class PreAccessCodec implements Codec {
	public PreAccessCodec(){
		supportedIns = new Format[] { new RGBFormat()};
	}
	
	protected Image accessFrame(Buffer frame){
		long t = (long) (frame.getTimeStamp() / 10000000f);
		 
		System.err.println(
			"Pre: frame #: "
				+ frame.getSequenceNumber()
				+ ", time: "
				+ ((float) t) / 100f
				+ ", len: "
				+ frame.getLength());
		return null;
	}
	
	@Override
	public int process(Buffer in, Buffer out) {
		// This is the "Callback" to access individual frames.
		Image image = accessFrame(in);
		Buffer b = in;
		if (image != null){
			b = ImageToBuffer.createBuffer(image, 25);
		}
		
		// Swap the data between the input & output.
		Object data = b.getData();
		in.setData(out.getData());
		out.setData(data);
		
		// Copy the input attributes to the output
		out.setFlags(in.getFlags());
		out.setFormat(b.getFormat());
		out.setLength(b.getLength());
		out.setOffset(b.getOffset());
		out.setTimeStamp(in.getTimeStamp());
		return BUFFER_PROCESSED_OK;
	}
	
	
	protected Format supportedIns[] = new Format[] { new VideoFormat(null)}; 
	protected Format supportedOuts[] = new Format[] { new VideoFormat(null)};
	Format input = null, output = null;
	
	@Override
	public Format[] getSupportedInputFormats() {
		return supportedIns;
	}

	@Override
	public Format[] getSupportedOutputFormats(Format in) {
		if (in == null)
			return supportedOuts;
		else {
			// If an input format is given, we use that input format
			// as the output since we are not modifying the bit stream
			// at all.
			Format outs[] = new Format[1];
			outs[0] = in;
			return outs;
		}
	}

	

	@Override
	public Format setInputFormat(Format format) {
		input = format;
		return input;
	}

	@Override
	public Format setOutputFormat(Format format) {
		output = format;
		return output;
	}

	

	@Override
	public String getName() {
		return "Pre-Access Codec";
	}

	@Override
	public void open() throws ResourceUnavailableException {}

	@Override
	public void close() {}
	
	@Override
	public void reset() {}

	@Override
	public Object getControl(String arg0) {
		return null;
	}

	@Override
	public Object[] getControls() {
		return new Object[0];
	}

}
